package com.blacktea.shardingjdbc.config;

import cn.hutool.core.date.DateUtil;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.*;

/**
 * @description:
 * @author: black tea
 * @date: 2021/9/22 13:36
 */
public class BirthdayAlgorithm implements PreciseShardingAlgorithm<Date> {

    List<Date> dateList = new ArrayList<>();
    {
        Calendar calendar2 = Calendar.getInstance();
        calendar2.set(2021, 1, 1, 0, 0, 0);
        Calendar calendar3 = Calendar.getInstance();
        calendar3.set(2022, 1, 1, 0, 0, 0);
        dateList.add(calendar2.getTime());
        dateList.add(calendar3.getTime());
    }

    @Override
    public String doSharding(Collection<String> collection, PreciseShardingValue<Date> preciseShardingValue) {
        // 获取属性数据库的值
        Date date = preciseShardingValue.getValue();
        // 获取数据源的名称信息列表
        Iterator<String> iterator = collection.iterator();
        String target = null;
        for (Date s : dateList) {
            target = iterator.next();
            // 如果数据早于指定的日期直接返回true
            if (date.before(s)) {
                break;
            }
        }
        // 偷个懒,直接使用iterator的表名作为返回值
        return target;
//        return preciseShardingValue.getLogicTableName()+"_"+this.tableByDateYear(preciseShardingValue.getValue());
    }

    /**
     * 返回年月部分
     */
    private String tableByDateYear(Date date){
        return DateUtil.format(date,"yyyyMM");
    }
}
